package com.mcz.yun4book.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.mcz.yun4book.entity.Type;
import com.mcz.yun4book.service.TypeService;
import com.mcz.yun4book.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("type")
public class TypeController {
    @Autowired
    private TypeService typeService;
    @RequestMapping(value = "/list",produces = {"application/json"})
    @ResponseBody
    public Result<Type> list(int page, int limit, Type type){
        System.out.println(type);
        Result<Type> result=new Result<>();
        Page<Type> pageInfo=typeService.findAllType(page, limit,type);
        result.setData(pageInfo.toList());
        result.setCount(pageInfo.getTotalElements());
        return result;
    }

    @GetMapping("list")
    public String toListPage(){

        return "type/list";
    }
    @GetMapping("add")
    public String toAdd(){
        return "type/add";
    }

    @PostMapping("add")
    @ResponseBody
    public Result doAdd(@RequestBody Type type){

        Result result=new Result<>();
        result.setMsg("添加成功");
        Type ret=typeService.addType(type);
        if(type==null){
            result.setCode(1);
            result.setMsg("添加失败");
        }
        return  result;
    }
    @GetMapping("edit")
    public String toEdit(int id, Model model) throws JsonProcessingException {
        Type type=typeService.findTypeId(id);
        //转成JSON格式
        model.addAttribute("type",new ObjectMapper().writeValueAsString(type));
        return "type/edit";
    }
    @PutMapping("edit")
    @ResponseBody
    public Result doEdit (@RequestBody Type type){

        Result result = new Result<>();
        result.setMsg("编辑成功");
        Type ret = typeService.editType(type);
        if (ret == null) {
            result.setCode(1);
            result.setMsg("编辑失败");
        }
        return result;
    }
    @DeleteMapping("del")
    @ResponseBody
    public Result del(int id){
        Result result=new Result<>();
        int ret=typeService.delTypeById(id);
        if(ret==0){
            result.setCode(1);
            result.setMsg("删除失败");
        }
        return  result;
    }
}
